package cn.hd01.web.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hd01.common.BaseConstant.RebateSummaryType;
import cn.hd01.common.BaseConstant.WithdrawStatus;
import cn.hd01.common.BaseConstant.backendType;
import cn.hd01.model.WithdrawStatusModel;
import cn.hd01.repository.entity.Customer;
import cn.hd01.repository.entity.CustomerBankCard;
import cn.hd01.repository.entity.RebateBook;
import cn.hd01.repository.entity.RebateSummary;
import cn.hd01.repository.entity.User;
import cn.hd01.repository.entity.WithdrawBook;
import cn.hd01.service.CustomerBankCardService;
import cn.hd01.service.CustomerService;
import cn.hd01.service.RebateBookService;
import cn.hd01.service.RebateSummaryService;
import cn.hd01.service.WithdrawBookService;
import cn.hd01.util.CommonUtil;
import cn.hd01.web.auth.Auth;
import cn.hd01.web.util.WebConstant;
import cn.hd01.web.util.WebException;

@Controller
@RequestMapping("/withdrawBook")
@Auth
public class WithdrawBookController {
	
	@Autowired
	private WithdrawBookService withDrawBookService;
	
	@Autowired
	private RebateSummaryService rebateSummaryService;
	
	@Autowired
	private CustomerService customerService;
	
	@Autowired
	private RebateBookService rebateBookService;
	
	@Autowired
	private RebateSummaryService summaryService;
	
	@Autowired
	private CustomerBankCardService customerBankCardService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(Model m, HttpServletRequest request) {
		List<WithdrawStatusModel> list = new ArrayList<WithdrawStatusModel>(2);
		WithdrawStatusModel ws1 = new WithdrawStatusModel();
		WithdrawStatusModel ws2 = new WithdrawStatusModel();
		ws1.setStatus(WithdrawStatus.NOT);
		ws1.setName(WithdrawStatus.NOT_TEXT);
		
		ws2.setStatus(WithdrawStatus.SUCCESS);
		ws2.setName(WithdrawStatus.SUCCESS_TEXT);
		list.add(ws1);
		list.add(ws2);
		m.addAttribute("withdrawStatuss", list);
		return "withDrawBook";
	}

	@ResponseBody
	@RequestMapping(path = "/list", method = RequestMethod.GET)
	private Page<WithdrawBook> find(WithdrawBook wdb, @PageableDefault Pageable pageable, HttpServletRequest req) {
		
		String servantId = req.getParameter("servantId");
		
		User loginUser = (User) req.getSession().getAttribute(WebConstant.USER_SESSION_NAME);
		Integer type = CommonUtil.getLoginUserType(loginUser);

		if(backendType.TEACHER.equals(type) || StringUtils.hasText(servantId)){
			
			Integer searchId = StringUtils.hasText(servantId) ? Integer.valueOf(servantId) : loginUser.getId();
			
			List<Integer> distributorIdList = customerService.findDistributorIdByServantId(searchId);
			if(CollectionUtils.isEmpty(distributorIdList)){
				return new PageImpl<WithdrawBook>(new ArrayList<WithdrawBook>());
			}else{
				wdb.setDistributorIdList(distributorIdList);
			}
		} 
		
		return withDrawBookService.findAll(wdb, pageable); 
	}
	
	@ResponseBody
	@RequestMapping(path = "/save", method = RequestMethod.POST)
	private void save(String distributorPhoneNo, BigDecimal withdrawRebate){
		
		Customer customer = customerService.findByPhoneNo(distributorPhoneNo);
		if(customer == null){
			throw new WebException(HttpStatus.BAD_REQUEST, "通过电话号码找不到对应渠道商");
		}
		
		List<CustomerBankCard> cardList = customerBankCardService.findByCustomerId(customer.getId());
		if(CollectionUtils.isEmpty(cardList)){
		 throw new WebException(HttpStatus.BAD_REQUEST, "该渠道商无银行卡信息"); 
		}
		CustomerBankCard card = cardList.get(0);
		
		RebateSummary summary = summaryService.findByRefIdAndType(customer.getId(), RebateSummaryType.DISTRIBUTOR);
		if (summary == null || withdrawRebate.compareTo(summary.getAllRebate()) > 0) {
			throw new WebException(HttpStatus.BAD_REQUEST, "余额不足");
		}

		Date date = new Date();
		BigDecimal after = summary.getAllRebate().subtract(withdrawRebate);
		WithdrawBook wb = new WithdrawBook();
		wb.setWithdrawRebate(withdrawRebate);
		wb.setRefId(summary.getRefId());
		wb.setType(summary.getType());
		wb.setAfterAllWithdrawRebate(after);
		wb.setName(customer.getName());
		wb.setStatus(WithdrawStatus.SUCCESS);
		wb.setCreateTime(date);
		wb.setUpdateTime(date);
		wb.setBankCardNum(card.getBankCardNum());
		wb.setBankName(card.getBankName());
		wb.setCustomerName(customer.getName());
		
		summary.setAllWithdrawRebate(summary.getAllWithdrawRebate().add(withdrawRebate));
		summary.setAllWaitWithdrawRebate(summary.getAllRebate().subtract(summary.getAllWithdrawRebate()));
		
		summaryService.save(summary);
		withDrawBookService.save(wb);
		
		//流水
		RebateBook rebateBook = new RebateBook();
		rebateBook.setRefId(summary.getRefId());
		rebateBook.setName(summary.getName());
		rebateBook.setRebate(withdrawRebate.negate());
		rebateBook.setType(wb.getType());
		rebateBook.setRebateReason("佣金提现");
		rebateBook.setCreateTime(date);
		rebateBook.setUpdateTime(date);
		
		rebateBook.setAllRebate(summary.getAllWaitWithdrawRebate());
		rebateBookService.save(rebateBook);
	}
	
	@ResponseBody
	@RequestMapping(path = "/withDraw/{id}", method = RequestMethod.GET)
	private void updateStatus(@PathVariable("id") Integer id){
		WithdrawBook book = withDrawBookService.findOne(id);
		book.setStatus(WithdrawStatus.SUCCESS);
		withDrawBookService.save(book);
		
		Date date = new Date();
		
		RebateSummary rs = rebateSummaryService.findByRefIdAndType(book.getRefId(), book.getType());
		rs.setUpdateTime(new Date());
		rs.setAllWaitWithdrawRebate(rs.getAllWaitWithdrawRebate().subtract(book.getWithdrawRebate()));
		rs.setAllWithdrawRebate(rs.getAllWithdrawRebate().add(book.getWithdrawRebate()));
		rebateSummaryService.save(rs);
		
		//流水
		RebateBook rebateBook = new RebateBook();
		rebateBook.setRefId(rs.getRefId());
		rebateBook.setName(rs.getName());
		rebateBook.setRebate(book.getWithdrawRebate().negate());
		rebateBook.setType(book.getType());
		rebateBook.setRebateReason("佣金提现");
						
		rebateBook.setCreateTime(date);
		rebateBook.setUpdateTime(date);
		rebateBook.setAllRebate(rs.getAllWaitWithdrawRebate());
		rebateBookService.save(rebateBook);
	}
	
}
